<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2018/9/21
 * Time: 14:23
 */

namespace common\models\db;

use common\members\wodrow\tools\Model;
use GuzzleHttp\Client;
use yii\base\Exception;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;

/**
 * Class Smms
 * @package common\models\db
 *
 * @property int $urlUseTotal
 */
class Smms extends \common\models\db\tables\Smms
{
    /**
     * @param ActiveRecord $model
     * @param string $attribute
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function fileUploadToSmmsForAr(ActiveRecord &$model, $attribute)
    {
        if($_FILES){
            $f = UploadedFile::getInstance($model, $attribute);
            if($f){
                $path = \Yii::getAlias("@storage_root/tmp/{$f->name}");
                $f->saveAs($path);
                $smms = new self();
                $smms->uploadLocalFile($path);
                $model->$attribute = $smms->url;
            }
        }
    }

    const NAME = 'smms';
    const TITLE = 'sm.ms';
    const UPLOAD_URL = 'https://sm.ms/api/upload';

    /**
     * @param string $url
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function uploadFromUrl($url)
    {
        $body = fopen($url, 'rb');
        $this->uploadByBody($body);
    }

    /**
     * @param string $file
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function uploadLocalFile($file)
    {
        $body = fopen($file, 'rb');
        $this->uploadByBody($body);
    }

    /**
     * @param $body
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function uploadByBody($body)
    {
        $c = new Client();
        $r = $c->request('POST', self::UPLOAD_URL, [
            'multipart' => [
                [
                    'name'     => 'smfile',
                    'contents' => $body,
                ],
            ],
        ]);
        if(is_resource($body)) {
            fclose($body);
        }
        $r = $r->getBody();
        $r = json_decode($r);
        if ($r->code!='success'){
            echo self::TITLE."上传失败";
            var_dump($r);exit;
        }
        $this->code = $r->code;
        if (isset($r->data)){
            $_d = $r->data;
            $this->width = $_d->width;
            $this->height = $_d->height;
            $this->filename = $_d->filename;
            $this->storename = $_d->storename;
            $this->size = $_d->size;
            $this->path = $_d->path;
            $this->hash = $_d->hash;
            $this->url = $_d->url;
            $this->delete = $_d->delete;
        }
        if (isset($r->msg)){
            $this->msg = $r->msg;
        }
        if (!$this->save()){
            echo Model::getModelError($this);exit;
        }
    }

    /**
     * @return int
     */
    public function getUrlUseTotal()
    {
        $key = 'urlUseTotalDocusCache';
        $docus = \Yii::$app->cache->get($key);
        if (!$docus){
            $docus = Docu::find()->all();
            \Yii::$app->cache->set($key, $docus, 3600*2);
        }
        $c = User::find()->where(['avatar_url' => $this->url])->count();
        $c += Docu::find()->where(['pre_logo' => $this->url])->count();
        foreach ($docus as $k => $v){
            $c += substr_count($v->body, $this->url);
        }
        return $c;
    }

    /**
     * @throws Exception
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function beforeDelete()
    {
        if(parent::beforeDelete()){
            if ($this->urlUseTotal > 0){
                throw new Exception($this->url.": {$this->id}使用中，不能删除");
            }
            $client = new Client();
            $r = $client->request('GET', $this->delete);
            if ($r->getStatusCode()!=200){
                throw new Exception(self::TITLE." 删除失败");
            }
            return true;
        }
        return false;
    }
}